from database import *
from images import *
from user import *
import os
import StringIO

class Matcher:

	def __init__(self):
		self._database = Database()
		if not self._database.training_images_added():
			self._store_training_pictures()
		
	def _training_pictures_to_database(self, directory_path):
		dirlist = os.listdir(directory_path)	
		trainer = User(0, MALE_ID, FEMALE_ID)
		
		for filename in dirlist:
			fullpath = os.path.join(directory_path, filename)
			training_image = open(fullpath, 'r')
			p_train_image = PIL.Image.open(training_image)
			nn_compressed = trainer.nn_compress_image(p_train_image)
			self._database.add_training_image(filename, training_image, 
											  nn_compressed)
											  
	def _store_training_pictures(self):
		self._training_pictures_to_database(TRAINING_DIR)
		
	def save(self):
		self._database.save()
		
	def create_user(self, userid, gender, interestedin):
		user = User(userid, gender, interestedin)
		self._database.add_user(user)
		
	def delete_user(self, userid):
		self._database.delete_user(userid)
		
	def is_target_suitable(self, sourceid, targetid):
		source = self._database.get_user(sourceid)
		
		if sourceid == targetid:
			return float(MIN_RESPONSE), False
			
		target = self._database.get_user(targetid)
		
		return source.is_target_suitable(target)
		
	def get_valid_targets(self, sourceid, limit):
		source = self._database.get_user(sourceid)
		active_users = self._database.get_active_users()
		valid_targets = []
		
		i = 0
		for user in active_users.values():
			if sourceid == user.get_id():
				continue
			value, suitable = source.is_target_suitable(user)
			if suitable:
				valid_targets.append((user.get_id(), value))
				i += 1
				if i == limit:
					return valid_targets
					
		userids = self._database.get_inactive_users_ids()
		for userid in userids:
			user = self._database.get_user(userid, cached=False)
			value, suitable = source.is_target_suitable(user)
			if suitable:
				valid_targets.append((userid, value))
				i += 1
				if i == limit:
					return valid_targets
					
		return valid_targets
		
	def update_user_image(self, userid, image):
		user = self._database.get_user(userid)
		
		p_image = PIL.Image.open(StringIO.StringIO(image))
		nn_compressed = user.nn_compress_image(p_image)
		
		user.set_image(image)
		user.set_nn_compressed_image(nn_compressed)
		
	def train_user_bot(self, userid, imageid, response):
		user = self._database.get_user(userid)
		image, comp = self._database.get_training_image(imageid)
		user.train(image, comp, response)
		
	def set_method(self, userid, methodid):
		user = self._database.get_user(userid)
		user.set_method(methodid)
		
	def set_interestedin(self, userid, interestedin):
		user = self._database.get_user(userid)
		user.set_interestedin(interestedin)
		
	def set_gender(self, userid, gender):
		user = self._database.get_user(userid)
		user.set_gender(gender)

